/**
 * User: Phil
 * Date: 10/23/11
 * Time: 12:30 AM
 */

var Pile = Class.extend({
	init: function(card, qty, type) {
		this.card = card;
		this.quantity = qty;
		this.type = type;
	},
	removeCard: function() {
		//Decrement pile
		this.quantity -= 1;

		//Return card
		return this.card;
	}
});

var Supply = Class.extend({
	init: function() {
		//Piles
		this.piles = new Array();

		//Get Dominion base kingdom cards
		var kCards = this.getKingdomCards(DOMINION_CARDS);
		
		//Select 10 random Kingdom cards for supply pool
		for(var x=0;x < 10;x++) {
			//Pick random card from available stock until we have 10
			var rnd = Math.floor(Math.random()*kCards.length);

			//Create new pile with the default amount of that card
			var pile = new Pile(kCards[rnd], kCards[rnd].quantity, CardTypes.KINGDOM);
			this.piles.push(pile);
			kCards.remove(rnd);

			//Fire event
			$("#player_events").trigger("onNewSupply", [x, pile]);
		}

		//Add victory cards
		var vCards = this.getVictoryCards(DOMINION_CARDS);

		for(var y=0;y < vCards.length;y++) {
			var pile = new Pile(vCards[y], vCards[y].quantity, CardTypes.VICTORY);
			this.piles.push(pile);

			var index = this.piles.length + y;

			//Fire event
			$("#player_events").trigger("onNewSupply", [index, pile]);
		}

		//Add treasure cards
		var vCards = this.getTreasureCards(DOMINION_CARDS);

		for(var z=0;z < vCards.length;z++) {
			var pile = new Pile(vCards[z], vCards[z].quantity, CardTypes.TREASURE);
			this.piles.push(pile);

			var index = this.piles.length + z;

			//Fire event
			$("#player_events").trigger("onNewSupply", [index, pile]);
		}
	},
	//Pile index 0-9
	draw: function(pileIndex) {
		//Remove card
		var card = this.piles[pileIndex].card;
		this.piles[pileIndex].quantity--;

		//Check for game end - 3 piles empty

		return card;
	},
	getKingdomCards: function(set) {
		var cards = new Array();
		$.each(set, function(index, value) {
			var isKingdom = $.inArray(CardTypes.KINGDOM, value.types);

			//Add if found
			if(isKingdom >= 0) {
				cards.push(value);
			}
		});

		return cards;
	},
	getVictoryCards: function(set) {
		var cards = new Array();
		$.each(set, function(index, value) {
			var isKingdom = $.inArray(CardTypes.KINGDOM, value.types);
			var isVictory = $.inArray(CardTypes.VICTORY, value.types);

			//Add if victory and not kingdom
			if(isVictory >= 0 && isKingdom < 0) {
				cards.push(value);
			}
		});

		return cards;
	},
	getTreasureCards: function(set) {
		var cards = new Array();
		$.each(set, function(index, value) {
			var isKingdom = $.inArray(CardTypes.KINGDOM, value.types);
			var isTreasure = $.inArray(CardTypes.TREASURE, value.types);

			//Add if victory and not kingdom
			if(isTreasure >= 0 && isKingdom < 0) {
				cards.push(value);
			}
		});

		return cards;
	}
});
